﻿using Baidu.Aip.Speech;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Tts_Nb_Mgj
{
    
    public partial class _Tts : Form
    {
        private Tts _ttsClient;
        public _Tts()
        {
            InitializeComponent();
            _ttsClient = new Tts("TlxiLMmWi6ls0DwRH9mkZXPf", "aeab6985f57864da37286a5b1fa7c0d1");
        }

        /// <summary>
        /// 判断当前端口是否被占用
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public static bool PortInUse(int port)
        {
            bool inUse = false;

            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)
            {
                if (endPoint.Port == port)
                {
                    inUse = true;
                    break;
                }
            }
            return inUse;
        }

        /// <summary>
        ///
        /// </summary>
        private void BGW_Handle_DoWork(object sender, DoWorkEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TB_FILE_ADDRESS.Text) || string.IsNullOrWhiteSpace(TB_SERVER_POINT.Text))
            {
                BGW_Handle.ReportProgress(1, string.Format("端口或文件保存地址不可为空项"));
                return;
            }
            int _point;
            if (!int.TryParse(TB_SERVER_POINT.Text, out _point))
            {
                BGW_Handle.ReportProgress(1, string.Format("端口不是有效值"));
                return;
            }
            if (PortInUse(_point))
            {
                BGW_Handle.ReportProgress(1, string.Format("端口已被占用"));
                return;
            }
            BGW_Handle.ReportProgress(1, string.Format("启动侦听:{0}", TB_SERVER_POINT.Text));
            TcpListener tcpl = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), _point);
            tcpl.Start();
            while (!BGW_Handle.CancellationPending)
            {

                Socket s = tcpl.AcceptSocket();
                string remote = s.RemoteEndPoint.ToString();
                Byte[] stream = new Byte[1024];
                s.Receive(stream);
                BGW_Handle.ReportProgress(1, "接收来自[" + remote + "]信息");
                HandleModel hm = Tts_Gen(Encoding.UTF8.GetString(stream));
                s.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hm)));
                s.Shutdown(SocketShutdown.Both);
            }
            tcpl.Stop();
        }

        private HandleModel Tts_Gen(string messageS)
        {
            messageS = messageS.Replace("\0", "");
            if (messageS == "-1") { return null; }
            HandleModel hm = JsonConvert.DeserializeObject<HandleModel>(messageS);
            if (hm != null && !string.IsNullOrWhiteSpace(hm.TtsName))
            {
                // 可选参数
                var option = new Dictionary<string, object>()
            {
                {"spd", hm.Speed}, // 语速
                {"vol", hm.Vol}, // 音量
                {"per", hm.Per}  // 发音人，0为女声，1为男声，3为情感合成-度逍遥，4为情感合成-度丫丫
            };
                var result = _ttsClient.Synthesis(hm.TtsContent, option);
                bool state = false;
                if (result.ErrorCode == 0)  // 或 result.Success
                {
                    hm.TtsFile = TB_FILE_ADDRESS.Text + @"\" + hm.TtsName + ".voc";
                    if (!Directory.Exists(TB_FILE_ADDRESS.Text))
                    {
                        Directory.CreateDirectory(TB_FILE_ADDRESS.Text);
                    }
                    try
                    {
                        File.WriteAllBytes(hm.TtsFile, result.Data);
                        state = true;
                    }
                    catch { }
                }
                hm.State = state;
            }
            return hm;
        }

        private void BGW_Handle_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        /// <summary>
        ///启动按钮
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            //启动
            if (!BGW_Handle.IsBusy)
            {
                BGW_Handle.RunWorkerAsync();
            }
            else { MessageBox.Show("已启动"); }
        }

        private void BGW_Handle_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.UserState != null)
            {
                LB_EVENT_CONTROL.Items.Add(e.UserState.ToString());
                LB_EVENT_CONTROL.SelectedIndex = LB_EVENT_CONTROL.Items.Count - 1;
            }
        }

        private void _Tts_Load(object sender, EventArgs e)
        {

        }
    }
}